﻿using Microsoft.Xaml.Behaviors.Media;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Xps.Serialization;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

namespace Messenger.Utils
{
    //泛型类读取写入yaml文件，T为引用类型，且有一个无参构造函数。
    public class YamlFileService<T> where T : class,new()
    {
        protected string _filePath;
        public YamlFileService()
        {
            
        }
        public YamlFileService(string filepath)
        {
            _filePath = filepath;
        }
        /// <summary>
        /// 从指定的yaml文件中读取内容，并将其反序列化为类型 T 的对象。
        /// </summary>
        /// <param name="filepath">无参的是固定文件路径，有参的是动态文件路径</param>
        /// <returns></returns>
        #region
        public virtual T Read(string filepath) 
        {
            _filePath = filepath;
            return Read();
        }
        public virtual T Read() 
        {
            try
            {
                if (!File.Exists(_filePath)) throw new FileNotFoundException($"File is not found :{_filePath}");
                string yaml = File.ReadAllText(_filePath);//读取指定文件的所有文本内容并返回一个字符串。
                if(string.IsNullOrEmpty(yaml))
                {
                    return new T(); //创建一个新的泛型对象并返回；
                }
                var builder = CreateDeserializer();
                var item = builder.Deserialize<T>(yaml);
                return item;
            }
            catch 
            {
                throw new Exception();
            }
        }
        #endregion
        /// <summary>
        /// 将类型 T 的对象序列化为 YAML 格式，并写入指定文件。
        /// </summary>
        /// <param name="filepath">无参的是固定文件路径，有参的是动态文件路径</param>
        /// <returns></returns>
        #region
        public virtual void Write(T model) 
        {
            if (model == null) return;
            var builder = CreateSerializer();
            string yaml = builder.Serialize(model);
            File.WriteAllText(_filePath, yaml);

        }
        public virtual void Write(string filePath,T model) 
        {
            _filePath = filePath;
            Write(model);
        }
        #endregion

        /// <summary>
        /// 序列化与反序列化
        /// CamelCaseNamingConvention，实现 C# 属性名（PascalCase，如 ApiKey）与 YAML 键名（camelCase，如 apiKey）的自动映射。
        /// 确保对象与 YAML 文本之间的转换符合预期，并允许子类灵活定制转换规则。
        /// </summary>
        /// <returns></returns>
        #region
        protected virtual ISerializer CreateSerializer()
        {
            return new SerializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build();
        }
        protected virtual IDeserializer CreateDeserializer() 
        {
            return new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build();
        }
        #endregion
    }
}
